package com.zhu.interceptor;

import com.zhu.properties.JwtProperties;
import com.zhu.utils.JwtUtil;
import com.zhu.utils.ThreadLocalUtil;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

import java.util.HashMap;
import java.util.Map;

@Component
public class JwtTokenAdminInterceptor implements HandlerInterceptor {

    @Autowired
    private JwtProperties jwtProperties;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        try {
            // 1、从请求头中获取令牌
            String token = request.getHeader(jwtProperties.getAdminTokenName());
            Map<String, Object> map;
            if (token.equals("fixme")) {
                map = new HashMap<>() {{
                    put("id", 4);
                    put("username", "admin");
                }};
            } else{
                // 2、校验令牌
                map = JwtUtil.parseJWT(jwtProperties.getAdminSecretKey(), token);
            }
            ThreadLocalUtil.set(map);
            // 3、通过，放行
            return true;
        } catch (Exception ex) {
            // 4、不通过，响应401状态码
            response.setStatus(401);
            return false;
        }
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        ThreadLocalUtil.remove();
    }
}
